<template>
  <div class="loginbox">
    <el-row>
      <el-col :span="24"  style="text-align:center">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="账号" prop="name">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="psw">
            <el-input type="password" v-model="form.psw"></el-input>
          </el-form-item>
          <el-form-item label="">
            <el-button type="primary" style="width:300px" @click="goHome('form')">登录</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import crypto from 'crypto'
import Http from '@/Http/Http'
import {mapActions,mapGetters,mapState} from 'vuex'
export default {
  data() {
    const name = (rele,value,callback) => {
      if(value ===''){
        return callback(new Error('请输入账号'))
      } else {
        callback()
      }
    }
    const psw = (rele,value,callback) => {
      if(value ===''){
        return callback(new Error('请输入密码'))
      } else {
        callback()
      }
    }
    return {    
      form: {
        name:'',
        psw:''
      },
      rules:{
        name:[
          {validator:name,trigger:'blur'}
        ],
        psw:[
          {validator:psw,trigger:'blur'}
        ]
      }
    }
  },
  computed:{
    ...mapState(['xx'])
  },
  created(){
  },
  methods:{
    ...mapActions(['userNameFun']),
    goHome(val) {
      this.$refs[val].validate( (valid) => {
        if (valid) {
          const md5 = crypto.createHash("md5");
            md5.update(this.form.psw);
          const psw = md5.digest('hex')
          Http.loginIn({
            "username":this.form.name,
            "password":psw
          })
          .then( res => {
            if( res.data.code == 200){
              sessionStorage.setItem('cmsauth',res.data.data.token);
              sessionStorage.setItem('userName',res.data.data.nick);
              this.$store.commit('userNameFun',res.data.data.nick);
              sessionStorage.setItem('userSolt',JSON.stringify(res.data.data.hasPermission));
              this.$role = res.data.data.hasPermission
              this.$router.push('/Home/Homepage')
            } else {
              this.$message.error(res.data.message)
            }
          })
          .catch( error => {
            this.$message.error('服务器请求失败')
          })
        }
      })
    }
  }
}
</script>
<style>
.loginbox{
 
  height: 100vh;
  background:#e5e5e5;
  display: flex;
  	justify-content: center;
  	align-items: center;
}
</style>
